package net.cellobject.sqlitexmlbrowser.shared;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.eclipse.core.resources.IFile;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

public class XMLUtil {
	
	public static Document getDocument(IFile resourceXmlFile) throws ParserConfigurationException, SAXException {
		try {
			final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			final DocumentBuilder builder = factory.newDocumentBuilder();
			final Document xmlDocument = builder.parse(resourceXmlFile.getRawLocationURI().getPath());
			return xmlDocument;
		} catch (IOException e) {
			return null;//file doesn't exist
		}
	}
	
	public static void addTag(Document xmlDocument, Element parentElement, String tagName, String attributeName, String attributeValue){
		final Element childElement = xmlDocument.createElement(tagName);
		childElement.setAttribute(attributeName, attributeValue);
		childElement.appendChild(xmlDocument.createTextNode(" "));		
		parentElement.appendChild(childElement);
	}
	
	public static Element addTag(Document xmlDocument, Element parentElement, String tagName){
		final Element childElement = xmlDocument.createElement(tagName);	
		parentElement.appendChild(childElement);
		return childElement;
	}
	
	public static String serializeDocument(final Document document) {
		String xml = null;
		try {
			final TransformerFactory factory = TransformerFactory.newInstance();
			final Transformer transformer = factory.newTransformer();
			final Properties outFormat = new Properties();
			outFormat.setProperty(OutputKeys.INDENT, "yes");
			outFormat.setProperty(OutputKeys.METHOD, "xml");
			outFormat.setProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
			outFormat.setProperty(OutputKeys.VERSION, "1.0");
			outFormat.setProperty(OutputKeys.ENCODING, "UTF-8");
			transformer.setOutputProperties(outFormat);
			final DOMSource domSource = new DOMSource(document.getDocumentElement());
			final OutputStream output = new StringOutputStream();
			final StreamResult result = new StreamResult(output);
			transformer.transform(domSource, result);
			xml = output.toString();
		} catch (final TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (final TransformerException e) {
			e.printStackTrace();
		}
		return xml;
	}
}
